package com.dormitory.myt.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
/*@ControllerAdvice和@RestControllerAdvice的区别：
*  1 。。。它返回的是 ModelAndView 对象
* 2。。。@RestControllerAdvice
* 它返回的是json格式的@ResponseBody数据
* */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public R exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return R.error(ex.getMessage());
    }

    /**
     * 处理SQL异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public R exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //Duplicate entry 'zhangsan' for key 'employee.idx_username'
        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + "异常呀";
            return R.error(msg);
        }else{
            return R.error("其他异常呀");
        }
    }
}
